package com.lik888.service.impl;

import com.lik888.config.JwtProperties;
import com.lik888.entity.User;
import com.lik888.entity.UserLogin;
import com.lik888.entity.po.R;
import com.lik888.mapper.UserMapper;
import com.lik888.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lik888.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2025-10-24
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    private final JwtTool jwtTool;
    private final JwtProperties jwtProperties;
    private final AuthenticationManager authenticationManager;
    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public R Login(User user) {
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authentication);
        //判断是否认证成功
        if(!authenticate.isAuthenticated()){
            return R.error("验证失败");
        }
        SecurityContextHolder.getContext().setAuthentication(authentication);
        UserLogin loginuser = (UserLogin) authenticate.getPrincipal();
        //TODO 生成token 并返回

        Integer userid = loginuser.getUser().getUserid();
        String token = jwtTool.createToken(userid.longValue(), jwtProperties.getTokenTTL());

//        userVo.setToken(jwtTool.createToken(user.getUserid().longValue(), jwtProperties.getTokenTTL()));
        stringRedisTemplate.opsForValue().set("securitydemo:user:"+userid,token,30, TimeUnit.MINUTES);

        return R.ok(token);
    }
}
